package com.graphsql.gamesdk.dialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Html;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.graphsql.gamesdk.R;
import com.graphsql.gamesdk.base.BaseDialog;
import com.graphsql.gamesdk.callback.LoginCallback;
import com.graphsql.gamesdk.config.Config;
import com.graphsql.gamesdk.util.JsonUtils;
import com.graphsql.gamesdk.util.LogDebugger;
import com.graphsql.gamesdk.util.ResourceUtil;
import com.graphsql.gamesdk.util.StringUtils;
import com.graphsql.gamesdk.util.ToastUtil;

public class LoginDialog extends BaseDialog implements OnClickListener {
	// private static LoginDialog instance;

	private static final String TAG = "LoginDialog ";

	public static final String AGREEMENT_FILE = "agreement.html";

	public static boolean hasShowDialog;

//	private Context act;
	private Activity act;
	
	private LoginCallback mLoginCallback;
	private Button mLoginStart;
	private Button mLoginNext;
	private Button mLogin;
	private Button mRegister;
	private Button mLostPassword;
	private Button mGetCode;
	private Button mResetPw;
	private Button mActivate;
	private Button mGetRegisterCode;

	private EditText mPhone;
	private EditText mPassword;
	private EditText mCode;
	private EditText mActivateCode;
	private Button mCloseButton;
	private TextView mAgreement;
	private CheckBox mAgreementCheck;
	private EditText mCountryCode;
	private EditText mMyPhoneNumber;
	private ImageView mCountryCodeBtn;
	private LinearLayout mCountryCodePlate;
	private ScrollView mCountryCodePlateScroll;
	private RelativeLayout mAgreementPanel;
	

	private Button mRegisterNext;
	
	
	
	private String phoneNum = "";
	private String countryCode = "+86";
//	private ArrayList<CountryCodeModel> countryObjs = new ArrayList<CountryCodeModel>();
	
	private final int CODE_TIME_MAX = 60;
	private int getCodeTime = 0;

	protected int initLayoutId = 0;
    protected boolean autoLoginFlag = true;//本界面提供自动登录，需要显示用户协议
    
    private SmsContentObserver mSmsContentObserver ;
	
	@Override
	protected void onHandleMessage(Message msg) {
		if(hasShowDialog==false)return;
		switch (msg.what) {
		
		}
	}
	@Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	hasShowDialog = false;
        	//doToastAndCallback(-1, "登录窗口关闭。", new HashMap());
    		act.runOnUiThread(new Runnable() {
    			public void run() {
    				if (mLoginCallback != null) {
    					mLoginCallback.callback(-100, "登录窗口关闭。", new HashMap());
    				}
    			}
    		});
			LoginDialog.this.dismiss();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
	public void onClick(View v) {
		
	}

	public LoginDialog(Activity act, int theme,LoginCallback _callback) {
//		} 
		this(act,theme,0,true,_callback);
	}
	public LoginDialog(Activity act, int theme,int initLayoutId,boolean autoLoginFlag,LoginCallback _callback) {
		super(act, theme);
		this.act = act;
		this.setOwnerActivity(act);
		this.mLoginCallback = _callback;
//		if (initLayoutId==0) {
//			this.initLayoutId = ResourceUtil.getLayoutId(act, "gs_layout_login");
//		}else{
//			this.initLayoutId = initLayoutId;
//		}
		this.autoLoginFlag = autoLoginFlag;
//		phoneNum = SharedPreferencesUtil.getSharedPreferencesValue(act, Config.KEY_LOGIN_PHONE, "");
		this.setCanceledOnTouchOutside(false);
	    mSmsContentObserver = new SmsContentObserver(act,new Handler());
	    setContentView(R.layout.gs_layout_login);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	private void init() {
		
	}
	

	/**
	 * Called to tell you that you're stopping.
	 */
	protected void onStop() {
		super.onStop();
		Activity owner = getOwnerActivity();
        if (owner != null) {
        	try{
	        	owner.unregisterReceiver(mHandleSMSReceiver);//暂停时注销接收器
	        	if(mSmsContentObserver!=null)
	        	owner.getContentResolver().unregisterContentObserver(mSmsContentObserver);
        	}catch (Exception e) {
				e.printStackTrace();
			}
        }
	}

	@Override
	protected void onStart() {
		super.onStart();
		
	}
	@Override
	public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // getOwnerActivity() should be defined here if called via showDialog(), so do the related init here
        Activity owner = getOwnerActivity();
        if (owner != null) {
        	try{
	        	IntentFilter mIntentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
	    	    mIntentFilter.setPriority(Integer.MAX_VALUE);
	    	    owner.registerReceiver(mHandleSMSReceiver,mIntentFilter);//启动时接收器
	    		owner.getContentResolver().registerContentObserver( Uri.parse("content://sms/"),
	    	    		true, mSmsContentObserver);
        	}catch (Exception e) {
        		e.printStackTrace();
			}
        }
//        LoginInfoModel mLoginInfoModel =GamePlus.getLoginInfo(act);
//		String userid = mLoginInfoModel.getUserid();
//		String autokey = mLoginInfoModel.getAutokey();
//		final String phone = mLoginInfoModel.getPhone();
//		if(autoLoginFlag&&StringUtils.isNull(userid)==false&&StringUtils.isNull(autokey)==false){
//			if (!processingFlag) {
//				processingFlag = true;
////				RelativeLayout layout = new RelativeLayout(act);
////				initWarpWH(act);
////				this.setContentView(layout);
//				
//				my_autoLoginCallback _callback = new my_autoLoginCallback(){
//					@Override
//					public void callback(Map<?, ?> data) {
//						// TODO Auto-generated method stub
//						if(data==null||data.get("code")==null){
//							doToastAndCallback(-1, "网络超时，请稍候再试。", new HashMap<String, String>());
//							sendMessage(MESSAGE_AUTO_LOGIN_FAILURE);
//						}else if("0".equals(data.get("code"))==false){//请求出错 
//							if("18".equals(data.get("code"))){//token过期
//			                	GamePlus.resetSecureKey();
//							}
//							doToastAndCallback(-1, ""+data.get("message"), new HashMap<String, String>());
//							sendMessage(MESSAGE_AUTO_LOGIN_FAILURE);
//						}else{
//							String dataStr = (String)data.get("data");
//							try {//加密接口,返回数据需要解密
//								dataStr = DESUtil.des3decrypt(dataStr,Config.RANDOM_KEY);
//							} catch (Exception e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//								dataStr = "";
//							}
//							mLoginInfo = JsonUtils.bindData(dataStr, LoginInfoModel.class);
//							if(mLoginInfo==null){
//								doToastAndCallback(-1, "请求数据错误", new HashMap<String, String>());
//								sendMessage(MESSAGE_AUTO_LOGIN_FAILURE);
//							}else if("1".equals(mLoginInfo.getResult())){//注册失败 
//								doToastAndCallback(-1, ""+mLoginInfo.getMessage(), new HashMap<String, String>());
//								sendMessage(MESSAGE_AUTO_LOGIN_FAILURE);
//							}else{
////								ToastUtil.showMessage(act, "注册成功  id为"+mLoginInfo.getUserid());
//								mLoginInfo.setPhone(phone);
//								String activation = JsonUtils.getValue(dataStr,"activation");
//								if("1".equals(activation)){//是否需要激活 1表示需要激活，其他情况为不需要激活
//									sendMessage(MESSAGE_ACTIVATE);
//								}else{
//									sendMessage(MESSAGE_LOGIN_SUCCESS);
//								}
//							}
//						}
//						sendMessage(REMOVE_PROGRESS);
//					}
//				};
//				sendMessage(SHOW_PROGRESS);
//				GamePlus.my_autoLogin(this.getContext(), _callback, userid,autokey);
//			}
//		}
    }

	@Override
	public void show() {
		LogDebugger.println(TAG + " hasShowDialog=" + hasShowDialog);
		if (!hasShowDialog) {
			hasShowDialog = true;
			super.show();
		} else {
			this.dismiss();
		}
	}

	public void doToastAndCallback(final int code, final String msg,
			final Map<String, String> data) {
		ToastUtil.showMessage(act, msg);

		act.runOnUiThread(new Runnable() {
			public void run() {
				if (mLoginCallback != null) {
					mLoginCallback.callback(code, msg, data);
				}
			}
		});

	}
//	public void setSmsCode(String code){
//		sendMessage(SET_SMS_CODE,code);
//	}

	@Override
	public void dismiss() {
		super.dismiss();
	}
	
//	private void showCountryCodes() {
//		if (mCountryCodePlateScroll != null) {
//			hideKeyboard(mCountryCodePlateScroll);
//			if(countryObjs==null||countryObjs.size()<1){
//				if (!processingFlag) {
//					processingFlag = true;
//					my_getCountryCodesCallback _callback = new my_getCountryCodesCallback(){
//					@Override
//					public void callback(Map<?, ?> data) {
//						// TODO Auto-generated method stub
//						if(data==null||data.get("code")==null){
//							doToastAndCallback(-1, "网络超时，请稍候再试。", new HashMap<String, String>());
//						}else if("0".equals(data.get("code"))==false){//请求出错 
//							if("18".equals(data.get("code"))){//token过期
//			                	GamePlus.resetSecureKey();
//							}
//							doToastAndCallback(-1, ""+data.get("message"), new HashMap<String, String>());
//						}else{
//							String dataStr = (String)data.get("data");
//							GeneralModel mGeneralModel = JsonUtils.bindData(dataStr, GeneralModel.class);
//							if(mGeneralModel==null){
//								doToastAndCallback(-1, "请求数据错误", new HashMap<String, String>());
//							}else if("0".equals(mGeneralModel.getResult())){// 0:成功1:失败
//								String phone_codes = JsonUtils.getValue(dataStr, "phone_codes");
//								if(StringUtils.isNull(phone_codes)==false){
//									if(countryObjs==null){
//										countryObjs = new ArrayList<CountryCodeModel>();
//									}
//									countryObjs.clear();
//									countryObjs = (ArrayList<CountryCodeModel>)JsonUtils.bindDataList(phone_codes, CountryCodeModel.class);
//									sendMessage(MESSAGE_GET_COUNTRY_CODE_SUCCESS);
//								}
//							}else{//请求数据错误
//								doToastAndCallback(-1, ""+mGeneralModel.getMessage(), new HashMap<String, String>());
//							}
//						}
//						sendMessage(REMOVE_PROGRESS);
//					}
//				};
//				sendMessage(SHOW_PROGRESS);
//				GamePlus.my_getCountryCodes(this.getContext(), _callback);
//				}
//			}else{
//				sendMessage(MESSAGE_GET_COUNTRY_CODE_SUCCESS);
//			}
//		}
//	}
	private void hideCountryCodes() {
		if (mCountryCodePlateScroll != null) {
			mCountryCodePlateScroll.setVisibility(View.GONE);
		}
	}
//	private void addCountryCode(CountryCodeModel obj) {
//		if (mCountryCodePlate != null && obj!=null) {
//			LinearLayout item = (LinearLayout)this.getLayoutInflater().inflate(ResourceUtil.getLayoutId(act, "gl_login_country_code_item"), null, false);
//			TextView countrycode_txt = (TextView)item.findViewById(ResourceUtil.getId(act, "gl_item_countrycode"));
//			TextView countrycode_name = (TextView)item.findViewById(ResourceUtil.getId(act, "gl_item_countrycode_name"));
//			countrycode_txt.setText(obj.getCode());
//			countrycode_name.setText(obj.getCountry());
//			final String cCode = obj.getCode();
//			item.setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View view) {
//					countryCode = cCode;
//					mCountryCode.setText(cCode);
//					hideCountryCodes();
//				}
//			});
//			mCountryCodePlate.addView(item);
//		}
//	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		hideCountryCodes();
		return super.onTouchEvent(event);
	}
	
	private void hideKeyboard(View view){
		if(view!=null&&act!=null){
			//隐藏键盘
			InputMethodManager imm = (InputMethodManager)act.getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例 
			if (imm!=null&&imm.isActive()) { 
				imm.hideSoftInputFromWindow(mCountryCodePlateScroll.getWindowToken(), 0); 
			}
		}
	}
	
	private final BroadcastReceiver mHandleSMSReceiver = new BroadcastReceiver() {// 接收短信时的
																					// 接收器

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if ("android.provider.Telephony.SMS_RECEIVED".equals(action)) {
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					Object[] pdusObjects = (Object[]) bundle.get("pdus");
					SmsMessage[] messages = new SmsMessage[pdusObjects.length];
					for (int i = 0; i < pdusObjects.length; i++) {
						messages[i] = SmsMessage
								.createFromPdu((byte[]) pdusObjects[i]);
					}
					for (SmsMessage message : messages) {
						String body = message.getDisplayMessageBody();
						if (StringUtils.isNull(body) == false
								&& body.indexOf("盛大游戏") > -1) {
							int start = body.indexOf("验证码") + "验证码".length()
									+ 1;
//							setSmsCode(body.substring(start, start + 6));
							// ToastUtil.showMessage(DemoActivity.this,
							// ""+body,Toast.LENGTH_LONG);
						}
						LogDebugger.println("来信号码："
								+ message.getDisplayOriginatingAddress()
								+ "\n短信内容：" + message.getDisplayMessageBody());
					}
				}
			}
		}
	};

	// 观察者
	public class SmsContentObserver extends ContentObserver {

		private Context context;

		public SmsContentObserver(Context context, Handler handler) {
			super(handler);
			this.context = context;
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			// 读取收件箱中指定号码的短信
			String body = getSmsInPhone();
			// LogDebugger.info("SmsContentObserver", "onChange "+body);
			if (StringUtils.isNull(body) == false && body.indexOf("盛大游戏") > -1) {
				int start = body.indexOf("验证码") + "验证码".length() + 1;
//				setSmsCode(body.substring(start, start + 6));
				LogDebugger.println("短信内容：" + body);
				// ToastUtil.showMessage(DemoActivity.this,
				// ""+body,Toast.LENGTH_LONG);
			}
		}

		// 获取短信中最新的一条未读短信，大家可以去查查，一些字段
		public String getSmsInPhone() {
			final String SMS_URI_ALL = "content://sms/";
			// final String SMS_URI_INBOX = "content://sms/inbox";
			// final String SMS_URI_SEND = "content://sms/sent";
			// final String SMS_URI_DRAFT = "content://sms/draft";

			StringBuilder smsBuilder = new StringBuilder();

			try {
				ContentResolver cr = context.getContentResolver();
				String[] projection = new String[] { "_id", "address",
						"person", "body", "date", "type" };
				Uri uri = Uri.parse(SMS_URI_ALL);
				// type == 1 "接收"; ypeId == 2//"发送";
				Cursor cur = cr.query(uri, projection, "type = ?",
						new String[] { "1" }, "date desc");
				if (cur.moveToFirst()) {
					String smsbody;
					int smsbodyColumn = cur.getColumnIndex("body");
					do {
						smsbody = cur.getString(smsbodyColumn);
						smsBuilder.append(smsbody);
						if (smsbody == null)
							smsbody = "";
						break;
					} while (cur.moveToNext());
				} else {
					smsBuilder.append("no result!");
				}

			} catch (Exception ex) {
				LogDebugger
						.error("Exception in getSmsInPhone", ex.getMessage());
			}
			return smsBuilder.toString();
		}
	}
}
